package org.scohen.juploadr.uploadapi.flickrrest;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.scohen.juploadr.app.ImageAttributes;
import org.scohen.juploadr.app.PhotoSet;
import org.scohen.juploadr.ui.Task;
import org.scohen.juploadr.uploadapi.flickrrest.photosets.AddPhoto;

public class AddToPhotosetTask extends Task {
    private Collection sets;
    private RestFlickrApi api;
    private int numberOfSets;
    private boolean hasSetsToAdd;
    private String currentPhoto;
    private String currentSet;
    private int current = 0;

    public AddToPhotosetTask(Collection photoSets, RestFlickrApi api) {
        this.sets = photoSets;
        this.api = api;
        this.min = 0;
        this.max = getTotalNumberOfPhotosToAdd(photoSets);
        hasSetsToAdd = this.max != 0;
    }

    public String getTitle() {
        return Messages.getString("juploadr.flickrrest.task.addtophotoset.title", max);//$NON-NLS-1$ 
    }

    public void execute() {
        // now add the photos in the set
        Iterator iter = sets.iterator();
        while (iter.hasNext()) {
            PhotoSet set = (PhotoSet) iter.next();
            currentSet = set.getTitle();
            List<ImageAttributes> photos = set.getPhotos();
            for (ImageAttributes photo : photos) {             
                currentPhoto = photo.getTitle();
                updateProgress(++current);
                // the photo might not have uploaded yet if the user dropped it into the 
                // window during an upload. In this case, the photoId will be null.
                if (photo.getPhotoId() != null) {
                    if (!photo.getPhotoId().equals(set.getPrimaryPhotoId())) {
                        AddPhoto add = new AddPhoto(set, photo);
                        if (api.executeMethod(add)) {

                        }

                    }
                }
            }
        }
    }

    private int getTotalNumberOfPhotosToAdd(Collection sets) {
        Iterator iter = sets.iterator();
        int count = 0;
        while (iter.hasNext()) {
            PhotoSet set = (PhotoSet) iter.next();
            if (set.getPhotos().size() > 0) {
                numberOfSets++;
                count += set.getPhotos().size();
            }
        }
        return count;
    }

    public String getMessage() {
        return Messages
                .getString(
                        "juploadr.flickrrest.task.addtophotoset.dialog", (max - current) + 1, numberOfSets, currentPhoto, currentSet); //$NON-NLS-1$ 
    }

    public boolean hasSetsToAdd() {
        return hasSetsToAdd;
    }

}
